from sanic.views import HTTPMethodView
from sanic.response import text,json
import time
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id
import json as jn
import re
from processing.Sql_DataFrom import ProJosn


class addmemu(HTTPMethodView):
    async def post(self, request):
        html_data = request.json
        db = request.app.ctx.db
        # 查询a端所有账号信息
        # uid = html_data['uid']
        sql = f"""insert into authority_menus(title,menuType,name,icon,extraIcon,component,menuRank,
                    enterTransition,leaveTransition,activePath,hiddenTag,parentId,path,auths,frameLoading,showParent,frameSrc,
                redirect,fixedTag,keepAlive,showLink,uid,status,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) """
        db.insert(sql,
              (
               html_data['title'],
               html_data['menuType'] or 0,
               html_data['name'],
               html_data['icon'] or '',
               html_data['extraIcon'] or '',
               html_data['component'] or '',
               html_data['rank'] or 0,
               html_data['enterTransition'] or '',
               html_data['leaveTransition'] or '',
               html_data['activePath'] or "",
               html_data['hiddenTag'] or 0,
               html_data['parentId'] or 0,
               html_data['path'] or '',
               html_data['auths'] or 0,
               html_data['frameLoading'] or 0,
               html_data['showParent'] or 0,
               html_data['frameSrc'] or '',
               html_data['redirect'] or '',
               html_data['fixedTag'] or 0,
               html_data['keepAlive'] or 0,
               html_data['showLink'] or 0,
               html_data['parentId'] or 0,
               'normal')
                  )

        # 查询插入进去的菜单
        sql1 = """select * from authority_menus where title=%s """
        if db.find_one(sql1, html_data['title']):
            data = {
                'code': 200,
                'message': '插入成功'
            }
        else:
            data = {
                'code': 400,
                'message': '插入失败'
            }
        return json(data)
    

class memulist(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 查询a端所有账号信息
        list1 = []
        # 查询插入进去的菜单
        sql = """
            select * from authority_menus
            """
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        userInfo = db.find_all(sql)
        if userInfo:

            # 分页pageNum
            if pageNum == 1:
                sql += f" LIMIT {pageSize} "
            else:
                sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "
            # 这里俩字段互换了数据    uid和parentId
            userInfo = ProJosn(userInfo, ['id','title','menuType','name','icon','extraIcon','component','rank','enterTransition','leaveTransition','activePath','hiddenTag','uid',
            'path','auths','frameLoading','showParent','frameSrc','redirect','fixedTag','keepAlive','showLink','uid','ctime','status'],'list').to_dict(orient='records')

            for i in userInfo:
                i['children'] = []
                for j in userInfo:
                    if i['id'] == j['uid']:
                        i['children'].append(j)
                i['ctime'] = str(i['ctime'])
                if i['uid'] == 0 or i['uid'] == '0':
                    list1.append(i)
            tol = """ SELECT COUNT(*) FROM authority_menus where uid=0"""
            tol_data = db.find_one(tol)
            data = {
                'code': 200,
                'data':{
                    'data':list1,
                    'total': tol_data[0],
                },

                'message': '请求成功'
            }
        else:
            data = {
                'code': 200,
                'data': list1,
                'message': '请求成功'
            }

        return json(data)
    
class memudel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 查询a端所有账号信息
        html_data = request.json

        sql = "delete from authority_menus where id=%s"

        db.delete(sql,(int(html_data['id'])))

        sql1 = "select * from authority_menus where id=%s"
        if db.find_one(sql1, int(html_data['id'])):
            data = {
                'code': 400,
                'message': '删除失败!'
            }
        else:
            data = {
                'code': 200,
                'message': '删除成功!'
            }

        return json(data)
"""
    title,menuType,name,icon,extraIcon,component,menuRank,
                    enterTransition,leaveTransition,activePath,hiddenTag,parentId,path,auths,frameLoading,showParent,frameSrc,
                redirect,fixedTag,keepAlive,showLink,uid,status,ctime
"""
class memuupdate(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 查询a端所有账号信息
        html_data = request.json
        sql = """update authority_menus set title=%s,menuType=%s,name=%s,icon=%s,extraIcon=%s,component=%s,menuRank=%s,enterTransition=%s,leaveTransition=%s,activePath=%s,hiddenTag=%s,
            parentId=%s,path=%s,auths=%s,frameLoading=%s,showParent=%s,frameSrc=%s,redirect=%s,fixedTag=%s,keepAlive=%s,showLink=%s,uid=%s,ctime=now()
            where id=%s        
        """
        db.update(sql, (
            html_data['title'],
            html_data['menuType'] or 0,
            html_data['name'],
            html_data['icon'] or '',
            html_data['extraIcon'] or '',
            html_data['component'] or '',
            html_data['rank'] or 0,
            html_data['enterTransition'] or '',
            html_data['leaveTransition'] or '',
            html_data['activePath'] or "",
            html_data['hiddenTag'] or 0,
            html_data['parentId'] or 0,
            html_data['path'] or '',
            html_data['auths'] or 0,
            html_data['frameLoading'] or 0,
            html_data['showParent'] or 0,
            html_data['frameSrc'] or '',
            html_data['redirect'] or '',
            html_data['fixedTag'] or 0,
            html_data['keepAlive'] or 0,
            html_data['showLink'] or 0,
            html_data['parentId'] or 0,
            html_data['id']))

        sql1 = "select * from authority_menus where id=%s"
        if db.find_one(sql1, int(html_data['id'])):
            data = {
                'code': 200,
                'message': '编辑成功!'
            }
        else:
            data = {
                'code': 400,
                'message': '编辑失败!'
            }

        return json(data)

class rolelist(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        user_id = request.app.ctx.user_id
        # 查询a端所有账号信息
        list1 = []
        pageNum = int(request.args.get('pageNo',1))
        pageSize = int(request.args.get('pageSize',10))
        keyword = request.args.get('keyword', '')
        # 查询插入进去的菜单
        find_sql = """
                    select id,title,menu_list,name,status from authority_roles 
                """
        tol = """ SELECT COUNT(*) FROM authority_roles"""

        if keyword:
            find_sql += f" where title LIKE '%{keyword}%' or  name LIKE '%{keyword}%' "
            # 查询之后的总数据
            tol += f" where  title LIKE '%{keyword}%' or  name LIKE '%{keyword}%' "

        tol_data = db.find_one(tol)
        # 分页pageNum
        if pageNum == 1:
            find_sql += f" LIMIT {pageSize} "
        else:
            find_sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "
        sql_data = db.find_all(find_sql)
        roleData = ProJosn(sql_data,find_sql)

        data = {
            'code':200,
            'data':{
                'pageData': roleData,
                'total': tol_data[0]
            }
        }
        return json(data)

    async def put(self,request):
        db = request.app.ctx.db
        user_id = request.app.ctx.user_id
        html_data = request.json
        find_sql = """
            insert into authority_roles(title,menu_list,name,status,ctime) values(%s,%s,%s,%s,now())
        """
        permissionIds_str = ''

        if html_data['status']:
            status = 'normal'
        else:
            status = 'destroy'


        # 编码是唯一
        find_sql_code = """
            select * from authority_roles where title=%s
        """

        code = db.find_one(find_sql_code,html_data['title'])

        if code != None:
            data = {
                'code': 201,
                'message': '编码不能重复!'
            }
        else:
            if 'menu_list' in list(html_data):
                if len(html_data['menu_list']):

                    for i in range(0,len(html_data['menu_list'])):
                        if html_data['menu_list'][i] == 0:
                            continue
                        if i == 0:
                            permissionIds_str += str(html_data['menu_list'][i])
                        else:
                            permissionIds_str += ','+ str(html_data['menu_list'][i])
            db.insert(find_sql, (
                html_data['title'],
                permissionIds_str,
                html_data['name'],
                status
                )
                      )

            data = {
                'code': 200,
                'message':'添加成功!'
            }

        return json(data)

    async def post(self,request):
        db = request.app.ctx.db
        user_id = request.app.ctx.user_id
        html_data = request.json
        id = int(request.args.get('id'))
        sql = """update authority_roles set title=%s,menu_list=%s,name=%s,status=%s,ctime=now()
            where id=%s        
        """
        if html_data['status']:
            status = 'normal'
        else:
            status = 'destroy'

        permissionIds_str = ''
        if 'menu_list' in list(html_data):
            if len(html_data['menu_list']):

                for i in range(0,len(html_data['menu_list'])):
                    if html_data['menu_list'][i] == 0:
                        continue
                    if i == 0:
                        permissionIds_str += str(html_data['menu_list'][i])
                    else:
                        permissionIds_str += ','+ str(html_data['menu_list'][i])

        db.update(sql,(
            html_data['title'],
            permissionIds_str,
            html_data['name'],
            status,
            id
        ))


        data = {
            'code': 200,
            'message':'添加成功!'
        }
        return json(data)


    async def delete(self,request):
        db = request.app.ctx.db

        sql = "delete from authority_roles where id=%s"
        pageNum = int(request.args.get('id'))
        db.delete(sql, (int(pageNum)))
        data = {
            'code': 200,
            'message': '删除成功!'
        }
        return json(data)

class roleadd(HTTPMethodView):
    async def put(self, request):
        db = request.app.ctx.db
        html_data = request.json
        find_sql = """
                    insert into authority_roles(title,menu_list,name,status,ctime) values(%s,%s,%s,%s,now())
                """
        db.insert(find_sql,(
            html_data['title'],
            html_data['menu_list'],
            html_data['name'],
            'normal')
        )
        data = {
            'code':200,
            'message':'请求成功！'
        }
        return json(data)
    
class roledel(HTTPMethodView):
    async def delete(self, request):
        db = request.app.ctx.db
        # 查询a端所有账号信息
        html_data = request.json

        sql = "delete from authority_roles where id=%s"

        db.delete(sql, (int(html_data['id'])))

        sql1 = "select * from authority_roles where id=%s"
        if db.find_one(sql1, int(html_data['id'])):
            data = {
                'code': 400,
                'message': '删除失败!'
            }

        else:
            data = {
                'code': 200,
                'message': '删除成功!'
            }


        return json(data)
class roleedit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 查询a端所有账号信息
        html_data = request.json
        sql = """update authority_roles set title=%s,menu_list=%s,name=%s,ctime=now()
            where id=%s        
        """
        db.update(sql, (
            html_data['title'],
            html_data['menu_list'],
            html_data['name'],
            html_data['id']))

        sql1 = "select * from authority_roles where id=%s"
        if db.find_one(sql1, int(html_data['id'])):
            data = {
                'code': 200,
                'message': '编辑成功!'
            }
        else:
            data = {
                'code': 400,
                'message': '编辑失败!'
            }

        return json(data)
    
class allocation_users(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        # 查询a端所有账号信息
        html_data = request.json

        user_id = html_data['user_id']
        role_id = html_data['role_id']

        if role_id:
            find_sql = """
                    select id from ausers_roles where user_id=%s
                """

            if db.find_one(find_sql, (user_id)):
                sql = """
                    update ausers_roles set role_id=%s where user_id=%s
                """
                db.update(sql, (role_id, user_id))

            else:

                sql = """
                    insert into ausers_roles(user_id,role_id,ctime ) VALUES (%s,%s,now())

                """
                db.insert(sql, (user_id, role_id))

            sql1 = """
                    select * from ausers_roles where user_id=%s and role_id=%s
                """
            if db.find_one(sql1, (user_id, role_id)):
                data = {
                    'code': 200,
                    'message': '设置成功!'
                }
            else:
                data = {
                    'code': 400,
                    'message': '设置失败!'
                }
            return json(data)
        else:

            num = 0
            str_menu = ''
            for i in list(html_data['menu_list']):
                if num == 0:
                    str_menu += str(i)
                else:
                    str_menu += ',' + str(i)
                num += 1

            find_sql = """
                        select id from ausers_roles where user_id=%s
                    """
            if db.find_one(find_sql, (user_id)):

                sql = """
                    update ausers_roles set menu_list=%s where user_id=%s
                """
                db.update(sql, (str_menu,user_id))
                data = {
                    'code': 200,
                    'message': '设置成功!'
                }
                return json(data)
            else:
                data = {
                    'code': 302,
                    'message': '没有角色!'
                }
                return json(data)

class operation_log(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        html_data = request.json
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))

        sql = f"""
                        select user_id,visit_ip,visit_path,visit_param,visit_type,create_time from operation_log 
                """
        sql += f" ORDER BY create_time DESC "
        # 获取总数据
        tol = """ SELECT COUNT(*) FROM operation_log"""
        tol_data = db.find_one(tol)

        # 分页pageNum
        if pageNum == 1:
            sql += f" LIMIT {pageSize} "
        else:
            sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "

        # sql += f"  ORDER BY create_time ASC  "

        DataList = db.find_all(sql)
        DataList = ProJosn(DataList,sql, 'sql').to_dict(orient='records')

        data = {
            'code': 200,
            'data':DataList,
            'message': '请求成功!'
        }
        return json(data)

class error_log(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db
        html_data = request.json
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))


        sql = f"""
                    select error_content,error_path,visit_ip,create_time from error_log 
                """

        # 获取总数据
        tol = """ SELECT COUNT(*) FROM error_log"""
        tol_data = db.find_one(tol)
        sql += f" ORDER BY create_time DESC "
        # 分页pageNum
        if pageNum == 1:
            sql += f" LIMIT {pageSize} "
        else:
            sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "

        # sql += f"  ORDER BY create_time ASC  "

        DataList = db.find_all(sql)
        DataList = ProJosn(DataList,sql, 'sql').to_dict(orient='records')

        data = {
            'code': 200,
            'data':DataList,
            'message': '请求成功!'
        }
        return json(data)
    
class distribution_menu(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        find_sql = """
                    update ausers_roles set menu_list=%s,ctime=now() where user_id=%s
                """
        db.update(find_sql,(html_data['menu_list'],html_data['user_id']))
        data = {
            'code':200,
            'message':'分配成功！'
        }
        return json(data)